function TransMat = EstTransMat1 (Pt, It,P,I)
% Estimates the transition matrix given a vector of DISCRETE prices
% Inputs:
%   Pt = Tx1 vector of observed price bins
%   It = Tx1 vector of intervals
% Assume that Pt and It are sorted by date and interval
% Estimating equation is xi: reg P_t+1 P_t P_t^2 i.I*P_t i.I*P_t^2
% Normal distribution of errors 


T = size(Pt,1);
% look at the next P
Pnext = Pt([ 2:end  1]);

% get the highest and lowest price bin
	%P_min = min(Pt);
	%P_max = max(Pt);

% CREATE VARIABLES
	% generate dummies
	Dummies = dummyvar(It);
	size(Dummies);
	Dummies = Dummies(:,2:end);  % drop one dummy, interval 1

	% generate the square of the bins
	Pt2 = Pt.*Pt;
	
	size(Dummies)
	size(Pt)
	uppity = repmat(Pt,1,I-1 );
	size(uppity)
	
	% create the interactions
	intPt = Dummies.*repmat(Pt,1,I-1 );
	intPt2 = Dummies.*repmat(Pt2,1,I-1);

	% create the matrix
	X = [ones(T,1),Pt,Pt2,Dummies, intPt, intPt2];


	% create the matrix
	X = X(1:(T-1),:);  % lop off last obs
	Pnext = Pnext(1:(T-1),1);

% ESTIMATE
	% estimate beta
	beta = inv(X'*X)*X'*Pnext;
	uhat = Pnext-X*beta;
	sigma = sqrt(sum(uhat.*uhat)/(size(X,1)));

% CONDITIONAL PROBABILITIES

	% stack discrete prices in order to make a matrix of each possible price/interval combination
	Ptvector = repmat((1:P)', I,1);   
	Pt2vector = Ptvector.*Ptvector;
    
	
	
	% make interval dummies in order to make a matrix of each possible
	% price/interval combination
	temp = (1:I)';
	Ivector = temp(:,ones(1,P)).';
	Ivector = Ivector(:);
	D = dummyvar(Ivector);
	D = D(:,2:end);  %cut out the dropped interval
	disp('1')
	size(D)
	
	% create the matrix of each possible interval and discrete price
	%X = [ones(P*I,1), Ptvector, Pt2vector, D];
	
	
	% with interactions
	InteractPt = D.*repmat(Ptvector,1,size(D,2));
	InteractPt2 = D.*repmat(Ptvector,1,size(D,2));
	
	% the matrix
	X = [ones(P*I,1), Ptvector, Pt2vector, D, InteractPt, InteractPt2];

	% get the predicted price using estimated parameters
	phat = X*beta;

  
% TRANSITION MATRIX
	% calculate the transitition matrix
	TransMat = zeros(P,P,I);
	% calculate the probability for each
	for i = 1:I
	    for p = 1:P
		%(1:P) is a row vector of price bins
		TransMat(p,:,i) = normpdf((1:P),phat(p+P*(i-1)),sigma)./sum(normpdf((1:P),phat(p+P*(i-1)),sigma));
	    end
	end


% from matlab help, residuals have different variances which depend on
% the value of their predictors (How?) (heteroskedasticity??)

